<?php


namespace support\controller;

use support\bootstrap\Event;
use support\exception\HttpException;
use support\Request;

abstract class Base
{
    /**
     * 不需要登录方法名
     * @var array
     */
    public $noNeedLogin = [];

    /**
     * 已经登录
     * @var array
     */
    public $excludeLogined = [];

    /**
    * 不需要鉴权方法名
    * @var array
    */
    public $noNeedRight = [];

    /**
     * 前置方法
     * @param Request $request
     */
    public function beforeAction(Request $request)
    {

    }

    protected function success($msg = '操作成功', $data = [], $code = 1)
    {
        $this->result($code, $msg, $data);
    }

    protected function error($msg = '操作失败', $data = [], $code = 0)
    {
        $this->result($code, $msg, $data);
    }

    protected function result($code, $msg, $data = [])
    {
        $res = [
            'code' => $code,
            'msg' => $msg,
            'data' => []
        ];
        if (!empty($data)) {
            $res['data'] = $data;
        }
        $request = request();
        $header = [];
        if ($request->expectsJson()) {
            $header['Content-Type'] = 'application/json';
        }
        throw new HttpException( json_encode($res, JSON_UNESCAPED_UNICODE), $code >= 1000 || $code < 200 ? 200 : $code,  $header);
    }

    /**
     * 后置方法
     * @param Request $request
     */
    public function afterAction(Request $request)
    {

    }

    public function event($event)
    {
        $eventInstance = Event::instance();
        $eventInstance->dispatch($event);
    }
}
